/*******************************************************************************
** CopyRight (c) 2005-2008 SKY-MOBI Ltd. All rights reserved.
** Filename:  debug.c
** Creator:   yuzhifeng
** Version:   0.0
** Date:      
** Description:
 *******************************************************************************/

#include "sgl_types.h"
#include "debug.h"

#define MAX_ASSERT_FILE_LEN    30*1024
#define ASSERT_FILE_NAME 		"coo20.log"
void sgl_assert(const char* file, int line, int exp)
{
	if(!exp)
	{
		int32 fd;
		int32 len = mrc_getLen(ASSERT_FILE_NAME);
		if(len > MAX_ASSERT_FILE_LEN)
			mrc_remove(ASSERT_FILE_NAME);
		fd = mrc_open(ASSERT_FILE_NAME, MR_FILE_WRONLY|MR_FILE_CREATE);
		if(fd)
		{
			char buf[100];
			len = sprintf(buf, "assert failed %s:%d\r\n", file, line);
			mrc_write(fd, buf, len);
			mrc_close(fd);
		}
		//SGL_DEBUG("assert failed %s:%d\n", file, line);
		mrc_exit();
	}
}

#ifndef _EXT_RELEASE

#define MAX_LOGFILE_SIZE	1024*10
void sgl_log(const char* file, void* buffer, int size)
{
	char tmp[32];
	int32 stream, sendbytes;
	char * data = (char*)buffer;
	if(size <= 0) return;

	if(mrc_getLen(file) > MAX_LOGFILE_SIZE)
	{
		SGL_STRCPY(tmp, file);
		SGL_STRCAT(tmp, ".bak");
		mrc_remove(tmp);
		mrc_rename(file, tmp);
	}
	
	stream = mrc_open(file, MR_FILE_WRONLY | MR_FILE_CREATE);
	if(stream)
	{
		mrc_seek(stream, 0, MR_SEEK_END);
		while(size > 0 && (sendbytes = mrc_write(stream, data, size)) >= 0) 
		{
			SGL_TRACE("sgl_log: %d, %d\n", size, sendbytes);
			size -= sendbytes;
			data += sendbytes;
		}
		mrc_close(stream);
	}
}

#endif

void file_log(char* buf, int32 value)
{
	char str[120];
	int32 fd = mrc_open("sky.log", MR_FILE_WRONLY | MR_FILE_CREATE);
	if(!buf || fd == 0)
		return;
	sprintf(str, "%s %d\r\n", buf, value);
	mrc_printf(str);
	mrc_seek(fd, 0, MR_SEEK_END);
	mrc_write(fd, str, strlen(str));
	mrc_close(fd);
}


